//
//  SWImagePickerController.swift
//  ChildStory
//
//  Created by linhan on 2016/11/7.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit

protocol SWImagePickerControllerDelegate:NSObjectProtocol
{
    func imagePickerController(_ picker: SWImagePickerController, didFinishPickingMediaWithPhotos photos: [SWALPhoto])
    func imagePickerControllerDidCancel(_ picker: SWImagePickerController)
}

class SWImagePickerController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,SWAssetsLibraryHelperDelegate,SWALPhotosCollectionViewControllerDelegate
{
    //是否可多选
    var allowsMultipleSelection:Bool = false
    var maxCount:Int = 1
    weak var delegate:SWImagePickerControllerDelegate?
    
    private var _groups:[SWALAlbum] = []
    
    
    
    lazy private var _tableView:UITableView = UITableView()
    lazy private var _deniedTipLabel:UILabel = UILabel()
    
    deinit
    {
        trace("DEINIT SWImagePickerController")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        createNavigationRightButton("取消", target: self, action: #selector(closeBtnTapped))
        
        //相册列表
        _tableView.frame = view.bounds
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = SWThemeStyle.CameraRollCellHeight
        _tableView.separatorColor = SWAppearanceManager.themeStyle.tableViewSeparatorColor
        _tableView.separatorInset = UIEdgeInsetsZero
        view.addSubview(_tableView)
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = UIEdgeInsetsZero
        }
        
        let WarningTextFont:UIFont = SWAppearanceManager.themeStyle.fontOfSize(15)
        _deniedTipLabel = UILabel.labelWithLimitWidth(view.frame.width - 20, text: "请到 设置-》隐私-》照片中设置允许使用你的照片", font: WarningTextFont)
        _deniedTipLabel.isHidden = true
        _deniedTipLabel.textColor = UIColor.darkGray
        _deniedTipLabel.textAlignment = .center
        view.addSubview(_deniedTipLabel)
        _deniedTipLabel.snp_makeConstraints({make in
            make.center.equalTo(view)
        })
        
        SWAssetsLibraryHelper.shared().addDelegate(self)
        SWAssetsLibraryHelper.shared().fetchAlbum()
    }
    
    //关闭
    func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    //选择某个相册
    private func selectAlbum(_ album:SWALAlbum, animated:Bool = true)
    {
        let viewController = SWALPhotosCollectionViewController(album:album)
        viewController.title = album.name
        viewController.maxCount = maxCount
        viewController.allowsMultipleSelection = allowsMultipleSelection
        viewController.delegate = self
//        viewController.cancelCallback = {[weak self] in self?.cancelCallback()}
//        viewController.chooseCallback = {[weak self] photos in
//            self?.chooseCallback(photos:photos)
//        }
        navigationController?.pushViewController(viewController, animated: animated)
    }
    
    private func cancelCallback()
    {
        delegate?.imagePickerControllerDidCancel(self)
    }
    
    private func chooseCallback(photos:[SWALPhoto])
    {
        delegate?.imagePickerController(self, didFinishPickingMediaWithPhotos: photos)
    }
    
    
    //MARK ============================================================================================
    //==============================              Delegate              ===============================
    //=================================================================================================
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWAlbumCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier:Identifier) as? SWAlbumCell
        if cell == nil
        {
            cell = SWAlbumCell(style: UITableViewCellStyle.default, reuseIdentifier: Identifier, cellWidth: view.width)
            cell?.accessoryType = .disclosureIndicator
        }
        (cell as? SWAlbumCell)?.album = _groups.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _groups.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at:indexPath, animated: true)
        if let album = _groups.valueAt(indexPath.row)
        {
            selectAlbum(album)
        }
    }
    
    //授权被拒绝
    func requestAuthorizationDenied()
    {
        _deniedTipLabel.isHidden = false
    }
    
    //相册获取完成
    func albumFetchComplete(_ album:[SWALAlbum], defaultAlbum:SWALAlbum?)
    {
        trace("albumFetchComplete", album.count)
        _groups = album
        _tableView.reloadData()
        if let defaultAlbum = defaultAlbum
        {
            selectAlbum(defaultAlbum, animated:false)
        }
    }
    
    func photosCollectionViewController(_ viewController: SWALPhotosCollectionViewController, didFinishChooseWithPhotos photos: [SWALPhoto])
    {
        delegate?.imagePickerController(self, didFinishPickingMediaWithPhotos: photos)
    }
    
    func photosCollectionViewControllerDidCancel(_ viewController: SWALPhotosCollectionViewController)
    {
        delegate?.imagePickerControllerDidCancel(self)
    }
    
    @objc private func closeBtnTapped()
    {
        delegate?.imagePickerControllerDidCancel(self)
    }
    
}




